<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="clientName">
            <el-input
              v-model="form.clientName"
              placeholder="请输入客户"
              type="input"
              style="width: 100%"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否加急" prop="clientName">
            <el-checkbox
              v-model="form.isUrgent"
              label="加急"
              :true-label="'1'"
              :false-label="'0'"
            ></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="groupBtns">
      <el-button-group>
        <el-button
          type="primary"
          size="mini"
          @click.native="getAdd()"
          icon="el-icon-circle-plus-outline"
        >
          添 加</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click.native="getGoodsAdd()"
          icon="el-icon-circle-plus-outline"
        >
          选 择</el-button
        >
        <el-button
          @click.native="delItem()"
          type="danger"
          size="mini"
          icon="el-icon-delete"
          >批 量 删 除</el-button
        >
      </el-button-group>
    </div>

    <el-table
      ref="itemTable"
      v-loading="loading"
      :data="lst"
      height="50vh"
      @selection-change="handleSelectionChange"
      @row-click="saveRow"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="型号"
        align="center"
        width="180"
        prop="modelNumber"
      >
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            style="width: 100%"
            v-model="scope.row.modelNumber"
            filterable
            placeholder="请选择型号"
            remote
            reserve-keyword
            :remote-method="getGoodsList"
            @change="handleGoods($event, scope.$index)"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            >
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.modelNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="length">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.length"
            size="small"
            placeholder="数量"
          />
          <span v-else>{{ scope.row.length }}</span>
        </template>
      </el-table-column>
      <el-table-column label="高度" align="center" prop="height">
        <template slot-scope="scope">
          <div v-if="scope.row.unit == '平方米'">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.height"
              size="small"
              placeholder="高度"
            />
            <span v-else>{{ scope.row.height }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="工艺要求" align="center" prop="technology">
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.technology"
            size="small"
            placeholder="工艺要求"
            style="width: 100%"
          >
            <el-option :label="'冷胶'" :value="0" />
            <el-option :label="'热胶'" :value="1" />
            <el-option :label="'先冷后热'" :value="3" />
            <el-option :label="'无工艺'" :value="2" />
          </el-select>
          <span v-else>{{ scope.row.technology | technologyFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="orderRemark"
        width="180"
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.orderRemark"
            size="small"
            placeholder="备注"
          />
          <span v-else>{{ scope.row.orderRemark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="img" width="60">
        <template slot-scope="scope">
          <el-image
            class="goodsImg"
            style="width: 40px; height: 40px"
            :src="scope.row.img"
            :preview-src-list="[scope.row.img]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
    </el-table>
    <!-- 选择货品 -->
    <el-dialog
      v-if="goodsVisible"
      title="样册备货"
      :append-to-body="true"
      :visible.sync="goodsVisible"
      width="72vw"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <selGoods ref="selGoods" :multi="1" type="墙布/样册" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="selGoods()">确 定</el-button>
        <el-button @click="goodsVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addOrderItem } from "@/api/qb";
import { getQbGoodsList } from "@/api/goods/qb";
import selGoods from "@/views/goods/qb/mods/select.vue";
export default {
  dicts: ["qb_order_state"],
  name: "RecordFormEdit",
  props: ["brandList"],
  components: { selGoods },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 表单参数
      form: {
        clientName: "备货",
        isUrgent: 0,
      },
      lst: [], //货品数据，防止污染
      goodsList: [],
      // 表单校验
      rules: {},
      selRow: [], //勾选行row
      goodsVisible: false,
    };
  },
  watch: {
    lst: function (val, oldVal) {
      if (val == undefined) {
        this.lst = [];
      }
      for (var i = 0; i < val.length; i++) {
        val[i].rownum = i;
      }
    },
  },
  mounted() {
    // 监听整个文档的点击事件
    document.addEventListener("click", this.handleDocumentClick);
  },
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener("click", this.handleDocumentClick);
  },
  methods: {
    // 新增行
    getAdd() {
      var objRow = {
        isEdit: false,
        productId: null,
        technology: 2,
        height: "2.8",
        variationStatus: "",
        price: 0,
        unit: "",
        discount: 0,
        subtotal: 0,
        img: null,
        modelNumber: "",
      };
      this.lst.push(objRow);
    },
    getGoodsAdd() {
      this.goodsVisible = true;
      this.$nextTick(() => {
        this.$refs.selGoods.getList();
      });
    },
    selGoods() {
      const selListVal = this.$refs.selGoods.$refs.selectVal.selection;
      if (!selListVal.length) {
        // this.$mount
        this.$message.error("请选择要添加的单据！！");
        return;
      }
      for (var i = 0; i < selListVal.length; i++) {
        var item = selListVal[i];
        let objRow = {
          isEdit: false,
          productId: item.productId,
          unit: item.unit,
          technology: 2,
          height:
            item.unit == "平方米"
              ? item.productType
                ? item.productType
                : 2.8
              : 1,
          length: 0,
          variationStatus: "",
          modelNumber: item.name,
          price: item.price,
          fabricType: item.fabricType,
          img: item.img,
          discount: 0,
          subtotal: 0,
        };
        this.lst.push(objRow);
      }
      this.goodsVisible = false;
    },

    // 删除行
    delItem() {
      var that = this;
      this.$confirm("是否确认删除，此操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 执行删除的方法
          for (var i = 0; i < that.selRow.length; i++) {
            var indexI = that.selRow[i];
            fn: for (var j = 0; j < that.lst.length; j++) {
              var indexJ = that.lst[j];
              if (indexI.rownum == indexJ.rownum) {
                // 判断item是否为id
                // if (!!indexJ.id) {
                //   deletOrderItem(indexJ.id).then((res) => {
                //     // this.$modal.msgSuccess("删除成功");
                //     // this.$emit("handleUpdate", this.form);
                //   });
                // }
                that.lst.splice(j, 1);
              }
            }
          }
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.selRow = val;
    },
    // 行点击事件
    saveRow(row) {
      for (var i = 0; i < this.lst.length; i++) {
        this.$set(this.lst[i], "isEdit", false);
      }
      if (!row.isEdit) {
        this.$set(row, "isEdit", true);
      } else {
        this.$set(row, "isEdit", false);
      }
      this.$forceUpdate();
    },
    handleDocumentClick(event) {
      // 检查点击事件是否发生在表格外
      if (!this.$refs.itemTable.$el.contains(event.target)) {
        // 鼠标点击在表格外部,关闭编辑行
        for (var i = 0; i < this.lst.length; i++) {
          this.lst[i].isEdit = false;
        }
      }
    },
    // 获取当前墙布货品信息
    getGoodsList(val) {
      var queryParams = {
        pageNum: 1,
        pageSize: 100,
        data: {
          name: val,
          namenum: null,
          fabricType: null,
          type: "墙布/样册",
          isuse: 1,
          typeNumber: null,
        },
      };
      getQbGoodsList(queryParams).then((res) => {
        this.goodsList = res.rows;
      });
    },
    handleGoods(val, rowIndex) {
      // console.log(val, rowIndex);
      var index = this.goodsList.findIndex((e) => e.productId == val);
      if (index != -1) {
        var item = this.goodsList[index];
        this.lst[rowIndex].modelNumber = item.name;
        this.lst[rowIndex].price = item.price;
        this.lst[rowIndex].productId = item.productId;
        this.lst[rowIndex].unit = item.unit;
        this.lst[rowIndex].fabricType = item.fabricType;
        this.lst[rowIndex].img = item.img;
      }
    },
  },
  filters: {
    technologyFormat(data) {
      var str = "";
      switch (data) {
        case 0:
          str = "冷胶";
          break;
        case 1:
          str = "热胶";
          break;
        case 2:
          str = "无工艺";
          break;
        case 3:
          str = "先冷后热";
          break;
        default:
          break;
      }
      return str;
    },
    dateFormat(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    discountFilt(val) {
      var value = 0;
      if (val >= 1 || !!val) {
        value = 0;
      } else {
        value = val;
      }
      return value;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}

::v-deep .el-table .success-row {
  background: #f0f9eb;
}
.groupBtns {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.priceInfo {
  span {
    display: inline-block;
    margin: 0 8px;
  }
}
::v-deep .el-form-item {
  margin-bottom: 10px !important;
}
.footFormContent {
  margin-top: 10px;
  ::v-deep .el-form-item {
    margin-bottom: 0px;
  }
  ::v-deep .el-form-item__label,
  ::v-deep .el-form-item__content {
    line-height: 24px;
  }
}
::v-deep .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style>
